<template>
  <el-dialog v-bind="{ ...$attrs }" class="app-add">
    <el-tabs type="card">
      <el-tab-pane label="修改用户">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon>
          <el-form-item label="域名" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" />
          </el-form-item>
          <!-- <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password" show-password />
            </el-form-item> -->
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="$emit('close')"> 关闭 </el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)"> 确认 </el-button>
    </template>
  </el-dialog>
</template>
 
<script lang="ts" setup>
import { reactive, ref, withDefaults, defineEmits, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { getDomainId, editDomain } from '@/server/domain'
import { ElMessage } from 'element-plus'
//定义自定义事件
const emit = defineEmits<{ (event: 'close'): void; (event: 'success'): void; }>()
const props = withDefaults(defineProps<Props>(), {
  id: ''
})
//定义属性
interface RuleForm {
  name: string,
  remark: string,
}
//表单
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
  name: '',
  remark: ''
})

const rules = reactive<FormRules<RuleForm>>({
  name: [{
    required: true,
    message: "请输入域名"
  }],
  remark: [{
    required: true,
    message: "请输入备注"
  }]
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!')
      try {
        await editDomain(props.id, ruleForm.value)
        ElMessage.success("修改成功")
        emit("success")

      } catch (err) {
        ElMessage.error("修改失败")
      }

    } else {
      console.log('error submit!', fields)
    }
  })
}
interface Props {
  id: string;
}

//获取用户
const getDomainIdData = async (id: string) => {
  const data = await getDomainId(id)
  ruleForm.value = data
  //  ruleForm.password=data.password
}
getDomainIdData(props.id)

watch(
  () => props.id,
  (newText, oldText) => {
    console.log('Text changed from', oldText, 'to', newText);
  },
  { immediate: true } // 立即执行回调一次，以处理初始值  
);  
</script>
<style lang="scss" scoped>
.el-dialog {
  height: 500px !important;
  overflow: auto;
  // .el-tabs{
  //   height: 400px;
  //   overflow: auto;
  // }
}
</style>